#include <windows.h>
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;

// GB2312转UTF-8，需用户手动delete
char *GBToUTF8(const char *gb2312)
{
    if (!gb2312 || strlen(gb2312) < 1)
        return 0;
 
    int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
    wchar_t *wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);
    MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    char *str = new char[len + 1];
    memset(str, 0, len + 1);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
    delete []wstr;
    return str;

}

int main(int argc, char *argv[])
{
    // 读取 GB2312 编码的 CSV 文件
    if (argc > 1)
    {
        if (strcmp(argv[1], argv[2]) == 0)
        {
            char new_filename[256];
            strcpy_s(new_filename, argv[1]);
            int length = strlen(new_filename);
            new_filename[length - 4] = '\0';
            strcat_s(new_filename, "_new.csv");
            ofstream outfile(new_filename);

            ifstream infile(argv[1]);
            // 打开 UTF-8 编码的 CSV 文件
            
            string line;
            // 逐行读取并转换
            while (getline(infile, line))
            {
                // 转换为 UTF-8 编码
                char *utf8 = GBToUTF8(line.c_str());

                // 写入 UTF-8 编码的 CSV 文件
                outfile << utf8 << endl;

                // 删除动态分配的内存
                delete []utf8;
            }

            infile.close();
            outfile.close();
            remove(argv[1]);
            rename(new_filename, argv[1]);
            return 0;
        }
        ifstream infile(argv[1]);
        // 打开 UTF-8 编码的 CSV 文件
        ofstream outfile(argv[2]);

        string line;
        // 逐行读取并转换
        while (getline(infile, line))
        {
            // 转换为 UTF-8 编码
            char *utf8 = GBToUTF8(line.c_str());

            // 写入 UTF-8 编码的 CSV 文件
            outfile << utf8 << endl;

            // 删除动态分配的内存
            delete []utf8;
        }

        infile.close();
        outfile.close();
    }

    return 0;
}